import { reactive, getCurrentInstance, onMounted, isReactive, markRaw } from 'vue';
export const useTransCoding = (columnDatas) => {
  const state = reactive({
    customTranData: {}
  });
  //码表接口请求
  const { proxy } = getCurrentInstance();
  const getCodeTableOptions = (codeType, codeItems) => {
    const keys = Object.keys(state.customTranData);
    let haveUpdate = false;
    if (keys && keys.length > 0) {
      haveUpdate = codeItems.some((item) => {
        let codeKey = item.codeKey || item.prop;
        return !keys.some((key) => codeKey === key);
      });
    }
    if (haveUpdate) {
      codeItems.forEach((item) => {
        let codeKey = item.codeKey || item.prop;
        let codeKeys = codeKey.toUpperCase();
        item.options = state.customTranData[codeKeys];
      });
    } else {
      if (proxy && proxy.$getCode) {
        proxy.$getCode({ codeType: codeType.join(',') }).then((res) => {
          const { options } = res || {};
          state.customTranData = res.data.data;
          codeItems.forEach((item) => {
            let codeKey = item.codeKey || item.prop;
            let itemData = res.data.data[codeKey.toUpperCase()].map((itemd) => {
              return {
                dispVal: itemd.dispVal || itemd.label || itemd[options?.labelKey],
                dataVal: itemd.dataVal || itemd.value || itemd[options?.valueKey]
              };
            });
            if (itemData && itemData.length) {
              item.options = itemData;
            } else {
              item.options = [];
            }
          });
        });
      }
    }
  };

  if (!Array.isArray(columnDatas) || !columnDatas.length) return;
  const arr = columnDatas.filter((item) => item.type === 'codeTable');
  if (arr.length > 0) {
    let codeList = arr.map((item) => item.codeKey || item.prop);
    if (codeList && codeList.length > 0) {
      getCodeTableOptions(codeList, arr);
    }
  }
};
